﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using Microsoft.WindowsLive.Id.Client;

namespace InsertFromSkyDrive
{
    public partial class WindowsLiveID : UserControl
    {
        PluginSettings m_settings;
        IdentityManager idmgr;
        Identity oID;
        TextBox m_tb;
        public string user = "";
        public string cid = "";
        public string Url = "";
        public bool auto = false;
        bool signin = false;
        bool IsOptions;

        public WindowsLiveID()
        {
            InitializeComponent();                
        }

        public void FirstRun(PluginSettings settings, bool isoptions, TextBox tb)
        {
            try
            {
                // Sets the variables that will appear in the Live ID window
                idmgr = IdentityManager.CreateInstance("ScottIsAFool;wlm@scottisafool.co.uk;Insert From SkyDrive Plugin",
                    "Insert From SkyDrive Plugin");
                oID = idmgr.CreateIdentity();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to initialise for the following reason: " + ex.Message, "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            m_settings = settings;
            IsOptions = isoptions;

            // Gets whether a WLID has been set to autosign in
            auto = m_settings.AutoSignIn;
            user = m_settings.User;
            cid = m_settings.CId;

            // Sets the signin value to be what the autologin value is.
            signin = auto;

            if (tb != null)
                m_tb = tb;

            LoadControl();
        }

        public void LoadControl()
        {

            // Shows the relevant screen for whether they're signed in or not
            ShowHide(signin);

            if (signin)
            {
                // If user has auto signed in, we need to get that information that is already stored
                grpSignedIn.Text = "Signed in as: " + user;
                
            }
            chbxAutoLogin.Checked = auto;

            // Sets whether the button to get files and folders is displayed
            // We don't want this on show if it's being looked at from the options window
            btnShowFiles.Visible = !IsOptions;

            if (!IsOptions)
            {
                // This section is for if it's *not* the options, ie it is being loaded from the plugin main window

            }
            else
            {

                // This section is for if it is the options window

            }
        }

        private void ShowHide(bool auto)
        {
            grpNotSignedIn.Visible = !auto;
            grpNotSignedIn.Enabled = !auto;
            grpSignedIn.Visible = auto;
            grpSignedIn.Enabled = auto;
            if (!auto)
            {
                grpNotSignedIn.Location = new System.Drawing.Point(3, 3);
            }
            else
            {
                grpSignedIn.Location = new System.Drawing.Point(3, 3);
            }
        }

        private void btnSignOut_Click(object sender, EventArgs e)
        {
            m_settings.AutoSignIn = false;
            m_settings.User = "";
            m_settings.CId = "";
            ShowHide(false);
            chbxAutoLogin.Checked = false;
            if (!auto)
                DoLogin();
            auto = false;
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void DoLogin()
        {
            // Check if a user is already signed in
            if (!oID.IsAuthenticated)
            {
                try
                {
                    // Opens the Sign in window. On successful sign in, oID.Authenticate()
                    // will return true.
                    if (oID.Authenticate())
                    {
                        // Change the label text to show we're signed in and as whom
                        cid = oID.cId; // This is then used to get the skydrive link for that user.
                        user = oID.UserName;
                        signin = true;
                        LoadControl();
                    }
                    else
                    {
                        MessageBox.Show("Authentication failed");
                    }
                }
                catch (WLLogOnException wlex)
                {
                    //Check to see if FlowUrl is defined.
                    if (wlex.FlowUrl != null)
                    {
                        //If FlowUrl is defined, direct user to the web page to correct the error.
                        MessageBox.Show(wlex.ErrorString + "Please go to " + wlex.FlowUrl.AbsoluteUri + "to correct the condition that caused the error", "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        //If FlowUrl is not defined, simply display the ErrorString.
                        MessageBox.Show(wlex.ErrorString);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was an error: " + ex.Message, "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

            }
            else
            {
                // This closes the active connection to the server
                oID.CloseIdentityHandle();
            }



        }

        private void chbxAutoLogin_Click(object sender, EventArgs e)
        {
            auto = chbxAutoLogin.Checked;
            if (!IsOptions)
            {
                if (chbxAutoLogin.Checked)
                {
                    m_settings.User = user;
                    m_settings.CId = cid;
                }
                else
                {
                    m_settings.CId = "";
                    m_settings.User = "";
                }
                m_settings.AutoSignIn = chbxAutoLogin.Checked;
            }
        }

        private void btnShowFiles_Click(object sender, EventArgs e)
        {
            using (frmBrowse browse = new frmBrowse(cid))
            {
                DialogResult browseresult = browse.ShowDialog();
                if (browseresult == DialogResult.OK)
                {
                    Url = browse.Url;
                    m_tb.Text = Url;
                }
            }
        }


    }
}
